<?php
namespace app\index\controller;
use app\index\controller\Base;
class Pay extends Base{
    
    public function index(){
        if(!$this->getLoginUser()){
            $this->error("请登录",url('user/login'));
        } 
        
        $orderId=input("get.id");
        $order=model("Order")->get($orderId);
        $dealId=$order->deal_id;
       // print_r($dealId);exit;
        $deal=model("Deal")->get($dealId);
        return $this->fetch("",[
          "order"=>$order,
          "deal"=>$deal,
      ]);  
     }
    
    
    public function paystatus(){
        if(!$this->getLoginUser()){
            $this->error("请登录",url('user/login'));
         }
         
        //模仿微信支付成功
        $id = input('post.id', 0, 'intval');
        //print_r($id);exit;
        if(!$id) {
            return showpay(0, 'error');
        }
       $order =model("Order")->get($id);  
        //print_r($User->email);exit;
       model("Order")->save(["pay_status"=>1],['id'=>$id]);
      //print_r($order->pay_status);exit;
        if($order->pay_status == 1) { // 支付成功
            return showpay(1, 'success');
        }
        //派发团购券并发送邮箱通知
          if(!empty($id)){
           return $this->updateconps($id);
         }
        return showpay(0, 'error'); 
    }
    
    public function updateconps($id){
       if(!$this->getLoginUser()){
            $this->error("请登录",url('user/login'));
        }
       $order =model("Order")->get($id);  
       $dealid=$order->deal_id;
       $userid=$order->user_id;
       $orderid=$id;
       $sn=$order->out_trade_no;
       $deal_count=$order->deal_count;
       $password=mt_rand(1000,10000); //随机密码
       $couponsdata=[
           "sn"=>$sn,
           "deal_id"=>$dealid,
           "user_id"=>$userid,
           "order_id"=>$orderid,
           "password"=>$password,
           "deal_count"=>$deal_count,
       ];
        //数据入库
       $couponsid=model("Coupons")->addone($couponsdata);
       //向用户发送邮件
       $coupons=model("Coupons")->get(['id'=>$couponsid]);
       $shownum=$coupons->sn;
       $pass=$coupons->password;
       $User=model("User")->get(['id'=>$userid]);
       $email=$User->email;
       $title="优惠券发送通知";
       $content="优惠券标号:'".$shownum."' 优惠券密码:'".$pass."'";
        \phpmailer\Email::send($email,$title,$content);
       //更改优惠券状态:已发送
   //   model("Coupons")->save(["status"=>1],["id"=>$couponsid]); 
        exit();
    }
    
    public function paysuccess(){
         if(!$this->getLoginUser()){
            $this->error("请登录",url('user/login'));
        } 
        return $this->fetch();
    }
}

